/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from "axios";
// import store from "@/store";
// import router from "@/router/router";
import { serialize } from "@/utils/util";
import { getToken } from "@/utils/auth";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { errorToast } from "@/utils/toast";
import Vue from "vue";
import { Toast } from "vant";

Vue.use(Toast);

// 设置超时时间
axios.defaults.timeout = 7000;

// 返回请求的状态码
axios.defaults.validateStatus = function(status) {
  return status >= 200 && status <= 500;
}

// 跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

// 初始化进度条为false
NProgress.configure({
  showSpinner: false
});

// HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start();//展示进度条
  const meta = config.meta || {};
  const isToken = meta.isToken === false;

  Toast.loading({
    message:"请等待...",
    mask:true,
    forbidClick:true,
    className:"default_loadding"
  })

  //设置token
  if (getToken() && !isToken) {
    let auth = "Authorization";
    config.headers[auth] = "Bearer " + getToken();
  }

  //headers中配置serialize为true开启序列化
  if (config.method === "post" && !meta.jsonFormat) {
    config.data = serialize(config.data);
  }

  //设置请求头
  if (config.method === "post" && meta.isFile && meta.jsonFormat) {
    config.headers["Content-Type"] = "multipart/form-data";
  }

  return config;
}, error => {
  Toast.clear();
  return Promise.reject(error);
});

//HTTPresponse响应拦截
axios.interceptors.response.use(res => {
  NProgress.done();
  // Toast.clear();
  const status = Number(res.status) || 200;
  const resultData = res.data;
  console.log(res)
  //如果是401则跳转到登录页面
  if (status === 401) {
    console.log("跳转到登录页");
  }
  // 如果请求为非200否者默认统一处理
  else if (status !== 200) {
    errorToast("打印错误信息");
    return Promise.reject("错误信息");
  }
  // 如果http请求状态是200，业务状态status非200，做抛出异常处理
  else if (status == 200 && resultData && resultData.status != 200) {
    // errorToast(resultData.error.msg);
    return Promise.reject("错误信息");
  }
  // 如果http请求状态是200，但是也没返回任何数据
  else if (status == 200 && !resultData) {
    errorToast("数据请求出错，请刷新重试")
    return Promise.reject("错误信息");
  }
  return resultData;
}, error => {
    NProgress.done();
    Toast.clear();
    return Promise.reject(new Error(error));
});

export default axios;
